<template>
  <div id="block">
    <div id="colorBlock_1" >
      <el-form
          v-loading="loading"
          :model="signInForm"
          :rules="rules"
          ref="SignInForm"
          label-width="100px"
          class="demo-dynamic">

        <el-form-item label="签到类型" prop="signInType">
          <el-select

              :popper-append-to-body="false"
              v-model="signInForm.signInType"
              placeholder="请选择签到类型">
            <el-option label="扫码签到" value="qrcode"></el-option>
            <el-option label="定位签到" value="location"></el-option>
            <el-option label="点击签到" value="click"></el-option>
            <el-option label="投票签到" value="vote"></el-option>
          </el-select>
        </el-form-item>

        <div v-if="signInForm.signInType==='vote'">
          <el-form-item label="投票问题" prop="voteQuestion">
            <el-input v-model="signInForm.voteQuestion"></el-input>
          </el-form-item>

          <el-form-item label="选项一" prop="voteOption1">
            <el-input v-model="signInForm.voteOption1"></el-input>
          </el-form-item>

          <el-form-item label="选项二" prop="voteOption2">
            <el-input v-model="signInForm.voteOption2"></el-input>
          </el-form-item>
        </div>

        <!--地图组件-->
        <div
            class="location"
            v-if="signInForm.signInType==='location' && this.located===false">
          <amap  @getPosition="getPosition" />
        </div>

        <!--定位完成后显示定位信息的修改按钮-->
        <div
            class="located"
            v-if="this.located===true">

          <el-button
              style="width: 98%;height: 40px;margin-left: 1%"
              type="primary"
              @click="locationEdit"
              icon="el-icon-location"
              round
              plain>
            {{ this.formattedAddress }}
          </el-button>

        </div>

        <el-form-item label="签到群组" prop="groupId">
          <el-select
              :popper-append-to-body="false"
              v-model="signInForm.groupId"
              placeholder="请选择签到群组">
            <el-option
                v-for="item in chats"

                :label="item.chatName"
                :value="item.chatId"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="发布时间">
          <el-switch
              v-model="publishNow"
              active-text="立即发布">
          </el-switch>
        </el-form-item>

        <el-form-item v-if="publishNow===false" prop="publishTime">
          <el-date-picker
              style="width: 100%;"
              v-model="signInForm.publishTime"
              :picker-options="pickerOptions"
              type="datetime"
              placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="限定时间">
          <el-slider
              :max="60"
              :min="1"
              :marks="marks"
              v-model="signInForm.limitTime"
              show-input></el-slider>
        </el-form-item>

        <el-form-item class="buttons">
          <el-button type="primary" @click="submitForm('SignInForm')">{{(!this.recordEdit)?'立即创建':'提交修改'}}</el-button>
          <el-button @click="cancel()">{{(!this.recordEdit)?'取消创建':'返回'}}</el-button>
        </el-form-item>


      </el-form>
    </div>
  </div>

</template>


<script>

import request from "@/utils/request";
import moment from 'moment';
import Amap from '@/components/Amap'

export default {
  name: "Publish",
  //组件注册
  components: {
    Amap
  },
  //百度地图获取经纬度
  mounted(){
    // var _this = this;
    // if(navigator.geolocation) {
    //   navigator.geolocation.getCurrentPosition(
    //       //locationSuccess 获取成功的话
    //       function(position) {
    //         _this.getLongitude = position.coords.longitude;
    //         _this.getLatitude = position.coords.latitude;
    //         alert(_this.getLongitude+','+_this.getLatitude)　　　　　 //弹出经度测试
    //
    //       },
    //       //locationError  获取失败的话
    //       function(error) {
    //         var errorType = ['您拒绝共享位置信息', '获取不到位置信息', '获取位置信息超时'];
    //         alert(errorType[error.code - 1]);
    //       }
    //   );
    // }
  },
  data() {
    //时间计算
    var verifyTime = (rule, value, callback) => {
      if (value) {
        let start = new Date(this.signInForm.publishTime).getTime();
        if (start < Date.now()) {
          callback("请选择未来的时间");
        } else {
          callback();
        }
      } else {
        callback("请选择发布时间");
      }
    };
    //startTime:(this.publishNow)?String(getTime()):String(this.publishTime) moment().format('YYYY-MM-DD HH:mm:ss')
    return {
      signInForm: {//签到发布的提交表单
        signInId:'',
        signInType:'qrcode',
        userId:'',
        useName:'',
        groupId:'',
        groupName:'',
        publishStatus:1,
        publishTime:'',
        startTime:'',
        limitTime:10,
        endTime:'',
        userLocation:'',
        voteQuestion:'',
        voteOption1:'',
        voteOption2:'',
        voteOption:'',
        voteResult:'[0,0]',
        expectNumber:0,
        signedNumber:0,
        unsignedNumber:0,
        result:'{}',
      },
      marks: {//限定时间标记
        10: {
          style: {color: '#1989FA'},
          label: this.$createElement('strong', '10分钟')
        }
      },
      pickerOptions:{//时间选择器的限制规则，只能选择当前时间以后的
        disabledDate(time){
          return time.getTime() < Date.now() - 3600 * 1000 * 24;
        }
      },
      rules: {//表单验证规则
        signInType:[{ required: true, message: '请选择签到类型', trigger: 'change' }],
        groupId:[{ required: true, message: '请选择签到群组', trigger: 'change' }],
        publishTime:[{validator: verifyTime, trigger: 'change'}],
        voteQuestion:[{ required: true, message: '请输入投票问题', trigger: 'blur' }],
        voteOption1:[{ required: true, message: '请输入选项', trigger: 'blur' }],
        voteOption2:[{ required: true, message: '请输入选项', trigger: 'blur' }],
      },
      chats:[{//可发布群组
        chatId:'',
        chatName:''
      }],
      publishNow:true,//立即发布
      recordEdit:false,//编辑页面标记
      located:false,//完成定位确定标记
      formattedAddress:'',//地图组件返回的详细地址
      loginId:sessionStorage.getItem("loginId"),//登录信息
      loading:false,//加载数据标记

    }
  },
  //初始化
  created() {
    if(this.$route.params.type){
      this.signInForm.signInType=this.$route.params.type//选择页跳转
    }

    if(this.$route.params.data!=null){ //未发布页跳转编辑
      this.signInForm=this.$route.params.data
      console.log(this.$route.params.data)
      this.signInForm.startTime=''
      // this.signInForm.publishTime=this.gotTime()
      this.recordEdit=true
      this.publishNow=false
      // this.signInForm.startTime[1]-=1
      //new Date(this.signInForm.publishTime).getTime()
      // this.signInForm.publishTime=moment(this.signInForm.startTime).format('yyyy-MM-DD HH:mm:ss')
      // this.signInForm.publishTime=this.gotTime()
      request.get("/chatInfo/chats/"+this.signInForm.userId).then(res =>{
        console.log(res)
        this.chats=res
      })

    }else{ //发布页初始化
      this.signInForm.userId=this.loginId
      this.signInForm.publishTime=this.gotTime()

      request.get("/chatInfo/chats/"+this.loginId).then(res =>{
        console.log(res)
        this.chats=res
      })
    }
  },
  methods: {
    //响应地图组件的定位信息
    getPosition({ address,lng , lat, name }) {
      this.formattedAddress = address;
      // this.postForm.longitude = String(lng);
      // this.postForm.latitude = String(lat);
      this.signInForm.userLocation=lng+','+lat;
      this.located=true
    },
    //已定位标记
    locationEdit(){
      this.located=false
    },
    //根据不同页面初始化表单并提交数据
    submitForm(SignInForm) {
      if(!this.recordEdit)this.signInForm.signInId=this.getSignInId();
      this.signInForm.startTime=(this.publishNow)?this.getTime():this.setTime();
      this.signInForm.publishStatus=(this.publishNow)?1:0;
      this.signInForm.endTime=this.getEndTime()
      this.signInForm.groupName=this.getChatName(this.signInForm.groupId)
      if(this.signInForm.signInType==='vote'){
        this.signInForm.voteOption=this.signInForm.voteOption1+'+'+this.signInForm.voteOption2
      }

      this.$refs['SignInForm'].validate((valid) => {
        if (valid) {
          if(this.publishNow){
            this.sendForm("/published")//发送到已发布数据库
          }else{
            this.sendForm("/unpublish")//发送到未发布数据库
          }
        } else {
          // alert('error submit!!');
          console.log('error submit!!');
          return false;
        }
      });
    },
    //根据发送的数据库名发送表单
    sendForm(where){
      this.loading=true
      request.post(where,this.signInForm).then(res =>{
        if(res){
          this.loading=false
          this.$message({
            message: (!this.recordEdit)?'创建成功':'修改成功',
            type: 'success'
          });

          // this.signInForm = {
          //   signInType:'',
          //   publishTime:this.gotTime(),
          //   userLocation: '',
          //   startTime:'',
          //   limitTime:10,
          //   endTime: ''
          // }
          // this.located=false

          if(where==='/published' && this.recordEdit){
            request.delete("/unpublish/del/"+this.signInForm.signInId).then(res =>{
              if(res){
                this.$message({message: '发布成功', type: 'success'});
                this.$router.push({name: 'Published',});
              }else{
                this.$message({message: '修改失败', type: 'danger'});
              }
            })
          }

          if(where==='/unpublish'){
            this.$router.push({name: 'Unpublished',});
          }else{
            this.$router.push({name: 'Published',});
          }


          if(this.recordEdit){
            this.$router.push({name: 'Unpublished',});
          }else{
            this.load()
          }
        }else{
          console.log('error save!!');
        }
      })
    },
    //取消提交，置空表单
    cancel(){
      // this.getEndTime()
      if(!this.recordEdit){
        this.signInForm = {
          signInType:'',
          publishTime:this.gotTime(),
          startTime:'',
          limitTime:10,
          endTime: ''
        }
        this.publishNow=true
      }else{
        this.$router.push({name: 'Unpublished',});
      }
    },
    //提交后页面数据刷新
    load(){
      this.signInForm.userId=this.loginId
      this.signInForm.publishTime=this.gotTime()

      request.get("/chatInfo/chats/"+this.loginId).then(res =>{
        console.log(res)
        this.chats=res
      })
      // request.get("/unpublish").then(res =>{
      //   console.log(res)
      //   this.signInForm.functionid=Object.keys(res).length+1
      // })
    },
    //获取当前时间的数据转为数据库的时间格式，用于立即签到的发布时间填值
    getTime() {
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth()+1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf = new Date().getMinutes()<10 ? parseInt('0'+new Date().getMinutes() ): new Date().getMinutes();
      let ss = new Date().getSeconds()<10 ? parseInt('0'+new Date().getSeconds() ): new Date().getSeconds();
      return  [yy,mm,dd,hh,mf,ss];
    },
    //获取当前时间转为yyyy-MM-DD HH:mm:ss格式，用于时间选择器的初始化
    gotTime(){
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth()+1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf = new Date().getMinutes()<10 ? '0'+new Date().getMinutes() : new Date().getMinutes();
      let ss = new Date().getSeconds()<10 ? '0'+new Date().getSeconds() : new Date().getSeconds();

      return yy+'-'+mm+'-'+dd+' '+hh+':'+mf+':'+ss;
    },
    //将yyyy-MM-DD HH:mm:ss格式转为数据库格式，用于时间选择器格式转为数据库时间格式
    setTime(){
      // alert(moment(this.signInForm.publishTime).format('YYYY-MM-DD HH:mm:ss'))
      var time_s =String(moment(this.signInForm.publishTime).format('YYYY-MM-DD HH:mm:ss')).replace(/\D/g,',').split(',')
      var time_i =[]
      for(var i=0;i<time_s.length;i++){
        time_i.push(parseInt(time_s[i]))
      }
      // alert(time_i.length+'  '+time_i)
      return time_i
    },
    //根据签到类型首字母和时间戳生成签到表id
    getSignInId(){
      let aa = this.signInForm.signInType.substring(0,1);
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth()+1;if(mm<10){mm='0'+mm}
      let dd = new Date().getDate();if(dd<10){dd='0'+dd}
      let hh = new Date().getHours();if(hh<10){hh='0'+hh}
      let mf = new Date().getMinutes()<10 ? '0'+new Date().getMinutes() : new Date().getMinutes();
      let ss = new Date().getSeconds()<10 ? '0'+new Date().getSeconds() : new Date().getSeconds();
      let ms = new Date().getMilliseconds();
      if(ms<10){ms='00'+ms}
      else if(ms<100){ms='0'+ms}

      return aa+yy+mm+dd+hh+mf+ss+ms
    },
    //根据发布时间和限制时间计算结束时间
    getEndTime(){
      this.signInForm.startTime=(this.publishNow)?this.getTime():this.setTime();

      var s_time=[]
      var l_time=this.signInForm.limitTime
      for(var i=0;i<this.signInForm.startTime.length;i++) s_time[i]=this.signInForm.startTime[i];

      var big=[1,3,5,7,8,10,12]
      var sml=[4,6,9,11]
      var is_big=false
      var is_sml=false
      for(i=0;i<big.length;i++){if(s_time[1]===big[i]) is_big=true}
      for(i=0;i<sml.length;i++){if(s_time[1]===sml[i]) is_sml=true}

      s_time[4]+=l_time
      if(s_time[4]>=60){
        s_time[4]-=60
        s_time[3]+=1
        if(s_time[3]>=24){
          s_time[3]-=24
          s_time[2]+=1

          if(is_big){
            if(s_time[2]>31){
              s_time[2]-=31
              s_time[1]+=1
              if(s_time[1]>12){
                s_time[1]-=12
                s_time[0]+=1
              }
            }
          }else if(is_sml){
            if(s_time[2]>30){
              s_time[2]-=30
              s_time[1]+=1
            }
          }else if(s_time[1]===2){
            if(s_time[0]%400===0 || (s_time[0]%4===0 && s_time[0]%100===0)){
              if(s_time[2]>29){
                s_time[2]-=29
                s_time[1]+=1
              }
            }else{
              if(s_time[2]>28){
                s_time[2]-=28
                s_time[1]+=1
              }
            }
          }

        }
      }

      // moment(s_time).add(l_time, 'minute')

      // var time_s =String(moment(s_time).add(l_time, 'minute').format('YYYY-MM-DD HH:mm:ss')).replace(/\D/g,',').split(',')
      // var time_i =[]
      // for(i=0;i<time_s.length;i++){
      //   time_i.push(parseInt(time_s[i]))
      // }
      // time_i[1]-=1
      // alert(this.signInForm.startTime)
      // alert(this.signInForm.startTime+'\n'+s_time)
      return s_time

      // alert(moment(s_time).add(l_time, 'minute'))
    },
    //根据获取的群组id从群组信息数组中返回群组名称
    getChatName(chatId) {
      for(var i=0;i<this.chats.length;i++){
        if(chatId===this.chats[i].chatId){
          return this.chats[i].chatName;
        }
      }
    }

  }
}
</script>

<style scoped>
#block{
  width: 100%;
  height: 700px;
}

#colorBlock_1{
  background-color: rgba(253, 252, 252, 0.8);
  max-width: 500px;
  min-width: 300px;
  min-height: 650px;
  width: 80%;
  height: 60%;
  margin: auto;
  margin-top: 10px;
  margin-bottom: 7%;
  border-radius: 10px;
  box-shadow: 2px 2px 3px rgba(192, 197, 194, 0.60);
}

.el-select{
  width: 100%;
}

.el-form-item{
  width: 95%;
  margin-top: 5%;
}

.el-form{
  position: relative;
  top: 15px;
}

.buttons{
  width: 100%;
  margin-top: 13%;
}

.el-button{
  width: 35%;
}

.location{
  /*background-color: rgba(179, 209, 197, 0.8);*/
  height: 330px;
  width: 100%;
  color: white;
  text-align: center;
  font-size: 20px;
  font-weight: lighter;
}


</style>